package com.gitee.xzb617.mybatis.sqllog.util;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.IOException;

/**
 * Json工具
 * @author xuzhibin
 */
public class JsonUtil {

    private final static ObjectMapper OBJECT_MAPPER = new ObjectMapper();

    /**
     * 对象转JSON字符串
     * @param obj 对象
     * @return
     */
    public static String toJson(Object obj) {
        try {
            return OBJECT_MAPPER.writeValueAsString(obj);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * JSON字符串转对象
     * @param strJson Json字符串
     * @param type 对象类型
     * @param <T>
     * @return
     */
    public static <T> T toObject(String strJson, Class<T> type) {
        try {
            return OBJECT_MAPPER.readValue(strJson, type);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 是否为json字符串，符合json规范
     * @param strJson
     * @return
     */
    public static boolean isJSONString(String strJson) {
        if (strJson==null || "".equals(strJson)) {
            return true;
        }
        final ObjectMapper mapper = new ObjectMapper();
        try {
            mapper.readTree(strJson);
        } catch (Exception e) {
            return false;
        }
        return true;
    }



}
